package com.yimin.floatball

import android.content.Context
import android.content.res.Resources
import android.graphics.PixelFormat
import android.os.Build
import android.util.Log
import android.view.Gravity
import android.view.WindowManager
import android.view.WindowManager.LayoutParams


object FloatWindowManager {

    var mBallView: FloatBallView? = null
    var mWindowManager: WindowManager? = null

    fun addBallView(context: Context) {
        if (mBallView == null) {
            val windowManager = getWindowManager(context)

            val resources = Resources.getSystem()
            val displayMetrics = resources.displayMetrics
            val screenWidth = displayMetrics.widthPixels
            val screenHeight = displayMetrics.heightPixels

            // 废弃
            // val screenWidth = windowManager.getDefaultDisplay().getWidth()
            // val screenHeight = windowManager.getDefaultDisplay().getHeight()

            Log.d(TAG, "screen: ${windowManager.getDefaultDisplay().getWidth()} : ${screenWidth}")

            val params = LayoutParams().apply {
                x = screenWidth
                y = screenHeight / 2
                width = LayoutParams.WRAP_CONTENT
                height = LayoutParams.WRAP_CONTENT
                gravity = Gravity.START or Gravity.TOP
                format = PixelFormat.RGBA_8888
                flags = LayoutParams.FLAG_NOT_TOUCH_MODAL or LayoutParams.FLAG_NOT_FOCUSABLE
                type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    // 需要system alert window权限
                    LayoutParams.TYPE_APPLICATION_OVERLAY
                } else {
                    // 低版本需要用
                    LayoutParams.TYPE_PHONE
                }
            }
            mBallView = FloatBallView(context)
            mBallView!!.setLayoutParams(params) // 保存，方便下次只修改坐标
            windowManager.addView(mBallView, params)
        }
    }

    fun removeBallView(context: Context) {
        if (mBallView != null) {
            val windowManager = getWindowManager(context)
            windowManager.removeView(mBallView)
            mBallView = null
        }
    }

    fun getWindowManager(context: Context): WindowManager {
        if (mWindowManager == null) {
            mWindowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        }
        return mWindowManager!!
    }

}
